package com.cloud.quickcommon.exception;


import com.cloud.quickcommon.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

/**
 * 全局异常处理器
 *
 * @author HQL
 * @version 1.0
 * @date 2019/6/14 14:35
 */
@Slf4j
@RestController
@ControllerAdvice(basePackages = {"com.cloud.quickcore.admin.controller","com.cloud.quickcore.shiro"})
public class GlobalExceptionHandler {
    /**
     * 表单效验异常
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R<String> bindingResultException(MethodArgumentNotValidException ex) {
        log.info("[全局异常] - 表单效验异常", ex.getMessage());
        if (ex.getBindingResult().hasErrors()) {
            return R.failed(ex.getBindingResult().getFieldError().getDefaultMessage());
        }
        return R.failed();
    }

    /**
     * 200 业务异常
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(BusinessException.class)
    public R<Void> businessException(BusinessException ex) {
        log.error("[全局异常] - 业务异常,{}", ex.getMessage());
        return R.failed(ex.getMessage());
    }
    /**
     * 权限验证异常
     * */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(UnauthorizedException.class)
    public R<Void> unauthorizedException(UnauthorizedException ex) {
        log.error("[全局异常] - 权限验证异常,{}", ex.getMessage());
        return R.failed("没有权限!");
    }

    /**
     * 500 空指针
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(NullPointerException.class)
    public R<Void> nullPointerException(NullPointerException ex) {
        log.error("[全局异常] - 空指针异常,{}", ex);
        return R.failed("空指针异常,请联系管理管");
    }

    /**
     * 500 运行时异常
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(RuntimeException.class)
    public R<Void> runtimeException(RuntimeException ex) {
        log.error("[全局异常] - 运行时异常", ex);
        return R.failed(ex.getMessage());
    }

    /**
     * 500 未知异常
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public R<Void> exception(Exception ex) {
        log.error("[全局异常] - 未知异常", ex);
        return R.failed(ex.getMessage());
    }
}
